from flask_restful import Resource, reqparse
from controller.module import api
from models.demo import Person
from service.demoService import DemoService


class DemoApi(Resource):
    def get(self,person_id):
        # 调用 service
        person = DemoService.query_person_by_id(person_id)

        if person is None:
            return {
                "code": 404,
                "message": "查无此项",
            }

        return {
            "code":200,
            "message":"查询成功！",
            "data":person.to_dict
        }



    def post(self):
        # 定义接收 json 中的数据项
        parser = reqparse.RequestParser()
        parser.add_argument('name', type=str, location='json')
        parser.add_argument('address', type=str, location='json')
        args = parser.parse_args()

        # 创建对象并为其属性赋值
        person = Person()
        person.name = args['name']
        person.address = args['address']

        # 调用 service
        try:
            DemoService.add_person(person)
        except:
            raise Exception("保存失败")

        return {
            "code":200,
            "message":"保存成功"
        }


api.add_resource(DemoApi,'/','/<int:person_id>')